import os
import re
import sys
import shutil
from epub_create import create_epub
from zip_epub import zip_epub

# 定义支持的文件编码列表
encodings = ['gbk', 'gb2312', 'utf-8', 'utf-16']

def create_xhtml(content, output_path, is_volume=False):
    """将内容转换为XHTML格式并保存到文件"""
    try:
        # 构建完整的XHTML结构
        body_class = ' class="volume"' if is_volume else ''
        xhtml_content = f'''<?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
        "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head><title></title>
        <link href="../Styles/fonts.css" type="text/css" rel="stylesheet"/>
        <link href="../Styles/content.css" type="text/css" rel="stylesheet"/>
        </head>
        <body{body_class}>
        {content}
        </body>
        </html>'''

        # 确保输出目录存在
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        
        # 直接写入文件
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(xhtml_content)
            
    except Exception as e:
        print(f"创建XHTML文件时出错: {str(e)}")
        raise  # 重新抛出异常以便上层处理


def process_novel(txt_path, novel_name):
    """处理小说文本文件，将其转换为XHTML格式

    Args:
        txt_path (str): 小说文本文件的路径
        novel_name (str): 小说名称

    Returns:
        tuple: 包含两个元素的元组:
            - list: 目录数据，包含卷和章节信息的列表
            - set: 卷前言内容的集合

    Raises:
        SystemExit: 当无法使用支持的编码读取文件时退出
    """
    # 创建输出目录
    output_dir = os.path.join(os.path.dirname(txt_path), f'{novel_name}_xhtml')
    os.makedirs(output_dir, exist_ok=True)

    # 读取小说内容
    content = None
    for encoding in encodings:
        try:
            with open(txt_path, 'r', encoding=encoding) as f:
                content = f.read()
                break
        except UnicodeDecodeError:
            continue

    if content is None:
        print(f"错误：无法使用以下编码读取文件 {txt_path}：{', '.join(encodings)}")
        print("请检查文件编码格式是否正确。")
        sys.exit(1)

    # 一级目录（卷、部）的正则表达式
    volume_pattern = r'(?:\n|\A)\s*(?:第[0123456789一二三四五六七八九十零〇百千两]*[卷部]|[卷][0123456789一二三四五六七八九十零〇百千两]*[部卷]).*(?:\n|\Z)'
    # 特殊篇章（序章、引子、番外等）的正则表达式
    special_chapter_pattern = r'(?:\n|\A)\s*(?:序章|引子|楔子|尾声|番外|后记|终章).*(?:\n|\Z)'
    # 二级目录（章、节等）的正则表达式
    chapter_pattern = r'^\s*(?:第[0123456789一二三四五六七八九十零〇百千两]*[章回节集]|\d{1,4}[：:]).*'

    # 添加调试信息
    print(f"开始处理小说：{novel_name}")

    # 先找出所有卷的位置
    volume_matches = []
    for match in re.finditer(volume_pattern, content, re.MULTILINE):
        # 清理卷名，移除多余空白字符
        clean_volume_title = ' '.join(match.group().strip().split())
        volume_matches.append((match.start(), clean_volume_title))

        # 添加调试信息
    if volume_matches:
        print(f"小说：{novel_name}，共找到 {len(volume_matches)} 卷")
        for i, (_, volume_title) in enumerate(volume_matches, 1):
            print(f"第 {i} 卷：{volume_title}")
    else:
        print(f"小说：{novel_name}，未找到卷信息，按章节处理")

    # 创建目录结构列表
    toc_data = []
    
    # 创建一个集合存储卷前言
    volume_prefaces = set()
    
    # 如果没有找到卷名，则直接按章节处理
    if not volume_matches:
        # 先分割特殊篇章和普通章节
        splits = re.split(f'({special_chapter_pattern}|{chapter_pattern})', content, flags=re.MULTILINE)
        current_chapter = 0
        
        # 获取总章节数
        total_chapters = len([x for x in range(1, len(splits), 2) if x < len(splits)])
        
        # 输出第一章和最后一章的信息
        if total_chapters > 0:
            first_chapter = splits[1].strip()
            last_chapter = splits[-2].strip() if len(splits) > 2 else first_chapter
            print(f"第一章：{first_chapter}")
            print("......")
            print(f"最后一章：{last_chapter}")
            print(f"总计：{total_chapters}章")

        for i in range(1, len(splits), 2):
            if i >= len(splits):
                continue

            current_chapter += 1
            chapter_title = splits[i].strip()
            chapter_parts = chapter_title.split(None, 1)
            chapter_number = chapter_parts[0]
            chapter_name = chapter_parts[1] if len(chapter_parts) > 1 else ""
            
            # 判断是否是特殊篇章
            is_special = bool(re.match(special_chapter_pattern, splits[i]))
            
            # 添加章节信息
            toc_data.append({
                'type': 'chapter',
                'title': f'{chapter_number} {chapter_name}',
                'file': f'chapter{current_chapter:04d}.xhtml'
            })
            chapter_content = splits[i + 1] if i + 1 < len(splits) else ""

            # 分离章节号和标题文字
            chapter_parts = chapter_title.split(None, 1)
            chapter_number = chapter_parts[0]
            chapter_name = chapter_parts[1] if len(chapter_parts) > 1 else ""

            # 创建带样式的章节标题HTML
            chapter_title_html = f'<h2 class="chapter"><span class="ch-index">{chapter_number}</span><br/>{chapter_name}</h2>'

            # 处理章节内容
            paragraphs = chapter_content.strip().split('\n')
            formatted_content = '\n'.join(
                [f'<p>{p.strip()}</p>' for p in paragraphs if p.strip()])

            # 创建章节的XHTML文件
            chapter_html = f'{chapter_title_html}\n{formatted_content}'
            chapter_path = os.path.join(
                output_dir, f'chapter{current_chapter:04d}.xhtml')
            create_xhtml(chapter_html, chapter_path)
    else:
        # 先找出所有特殊章节的位置
        special_matches = []
        for match in re.finditer(special_chapter_pattern, content, re.MULTILINE):
            special_matches.append((match.start(), match.group().strip()))
        
        # 合并卷和特殊章节的位置，按位置排序
        all_sections = volume_matches + special_matches
        all_sections.sort(key=lambda x: x[0])
        
        for i in range(len(all_sections)):
            current_volume = i + 1
            section_start, section_title = all_sections[i]
            
            # 判断是否是特殊章节
            is_special = bool(re.match(special_chapter_pattern, section_title))
            
            # 添加卷或特殊章节信息
            volume_data = {
                'type': 'volume',
                'title': section_title.strip(),
                'file': f'juan{current_volume}.xhtml',
                'chapters': [] if not is_special else None
            }
            
            # 确定当前章节的结束位置（找到下一行的开始）
            section_end = content.find('\n', section_start)
            if section_end == -1:
                section_end = len(content)

            # 如果有下一个章节，则当前章节的内容到下一个章节开始
            if i < len(all_sections) - 1:
                next_section_start = all_sections[i+1][0]
                section_content = content[section_end:next_section_start]
            else:
                # 最后一章节的内容到文件结束
                section_content = content[section_end:]

            print(f"处理{'特殊章节' if is_special else '卷'} {current_volume}: {section_title}")

            if not is_special:
                # 在卷内分割章节
                chapter_splits = re.split(
                    f'({chapter_pattern})', section_content, flags=re.MULTILINE)

                # 提取卷的前言内容（第一个章节之前的内容）
                volume_preface = chapter_splits[0].strip() if len(chapter_splits) > 0 else ""

                # 从前言中去除卷标题（如果存在）
                section_title_clean = section_title.strip()
                if volume_preface.startswith(section_title_clean):
                    volume_preface = volume_preface[len(section_title_clean):].strip()
            else:
                # 特殊章节不需要分割，整个内容就是章节内容
                volume_preface = section_content.strip()

            # 如果前言不为空，添加到集合中
            if volume_preface:
                volume_prefaces.add(volume_preface)

            # 创建标题HTML（使用指定的样式）
            title_html = f'''<div class="v-title">
            <h1 title="{section_title}" style="display:none"></h1>
            {section_title}
            </div>'''

            # 处理卷前言内容
            if volume_preface:
                preface_paragraphs = volume_preface.split('\n')
                # 使用class="v-content"作为除标题外内容的样式
                preface_formatted = '\n'.join(
                    [f'<p class="v-content">{p.strip()}</p>' for p in preface_paragraphs if p.strip()])

                # 创建XHTML文件（包含标题和内容）
                section_html = f'{title_html}\n{preface_formatted}'
                section_path = os.path.join(
                    output_dir, f'juan{current_volume}.xhtml')
                try:
                    create_xhtml(section_html, section_path, is_volume=True)
                except Exception as e:
                    print(f"创建XHTML文件失败: {str(e)}")
                    continue  # 跳过当前章节，继续处理下一个

            # 处理卷内的每个章节
            # 只有非特殊章节才需要处理内部章节
            if not is_special:
                current_chapter = 0
                for j in range(1, len(chapter_splits), 2):
                    if j >= len(chapter_splits):
                        continue

                    current_chapter += 1
                    chapter_title = chapter_splits[j].strip()
                    chapter_parts = chapter_title.split(None, 1)
                    chapter_number = chapter_parts[0]
                    chapter_name = chapter_parts[1] if len(chapter_parts) > 1 else ""
                    
                    # 添加章节信息
                    volume_data['chapters'].append({
                        'type': 'chapter',
                        'title': f'{chapter_number} {chapter_name}',
                        'file': f'juan{current_volume}_{current_chapter:04d}.xhtml'
                    })
                    chapter_content = chapter_splits[j +
                                                     1] if j + 1 < len(chapter_splits) else ""

                    # 分离章节号和标题文字
                    chapter_parts = chapter_title.split(None, 1)
                    chapter_number = chapter_parts[0]
                    chapter_name = chapter_parts[1] if len(chapter_parts) > 1 else ""

                    # 创建带样式的标题HTML（只包含章节名，不包含卷名）
                    title_html = f'<h2 class="chapter"><span class="ch-index">{chapter_number}</span><br/>{chapter_name}</h2>'

                    # 处理章节内容
                    paragraphs = chapter_content.strip().split('\n')
                    formatted_content = '\n'.join(
                        [f'<p>  {p.strip()}</p>' for p in paragraphs if p.strip()])

                    # 创建章节的XHTML文件
                    chapter_html = f'{title_html}\n{formatted_content}'
                    chapter_path = os.path.join(
                        output_dir, f'juan{current_volume}_{current_chapter:04d}.xhtml')
                    create_xhtml(chapter_html, chapter_path)

            toc_data.append(volume_data)
    
    # 返回目录数据和卷前言集合
    return toc_data, volume_prefaces

def process_and_create_epub(txt_path, novel_name, author_name, desc, cover_image_path, back_image_path):
    # 处理txt文件并获取目录数据和卷前言
    toc_data, volume_prefaces = process_novel(txt_path, novel_name)
    
    # 定义临时文件夹路径
    target_dir = os.path.join(os.path.dirname(txt_path), novel_name)
    xhtml_dir = os.path.join(os.path.dirname(txt_path), f'{novel_name}_xhtml')
    
    try:
        result = create_epub(txt_path, novel_name, author_name, toc_data, volume_prefaces, cover_image_path, back_image_path, desc)
        if result:
            # 压缩生成的文件夹
            zip_epub(target_dir, novel_name, author_name)
            return True
        return False
    except Exception as e:
        print(f"创建EPUB时发生错误: {str(e)}")
        return False
    finally:
        # 无论成功与否，都清理临时文件夹
        if os.path.exists(target_dir):
            try:
                # shutil.rmtree(target_dir)
                print(f"已清理临时文件夹: {target_dir}")
            except Exception as e:
                print(f"清理临时文件夹失败: {str(e)}")
        
        if os.path.exists(xhtml_dir):
            try:
                shutil.rmtree(xhtml_dir)
                print(f"已清理XHTML临时文件夹: {xhtml_dir}")
            except Exception as e:
                print(f"清理XHTML临时文件夹失败: {str(e)}")

# 使用示例
if __name__ == '__main__':
    novel_path = r'C:\Users\12035\Desktop\123\诡秘之主.txt'  # 替换为你的小说文件路径
    novel_name = '诡秘之主'  # 替换为你的小说名
    author_name = '爱潜水的乌贼'  # 替换为你的作者名
    desc = (
        '蒸汽与机械的浪潮中，谁能触摸非凡。又是谁在耳语？我从诡秘中醒来，睁眼看见这个世界：\n'
        '枪械，大炮，巨舰，飞空艇，差分机；魔药，占卜，诅咒，倒吊人，封印物……'
        '光明依旧照耀，神秘从未远离，这是一段"愚者"的传说。\n'
        '黑铁纪元，七位正统神灵与四大国统治着北大陆。蒸汽与机械的浪潮中，'
        '工业化社会迅速发展成形，而在看似平静繁荣的表面下，则是一个神秘扭曲，乃至疯狂的非凡世界。'
    )
    process_and_create_epub(novel_path, novel_name, author_name, desc, r'C:\Users\12035\Desktop\123\cover.jpg', r'C:\Users\12035\Desktop\123\bg1.jpg')

